/**
 * 维护企业微信“聚焦模式”状态
 *
 * 聚焦模式：只查看指定企业微信的消息
 */
import { Service } from '@gnlab/utils'
import { MemSubject, mmergeMap, mmap } from '@gnlab/utils/rx'
import { type Services } from '@/services'
import { API } from '@/services/common/api'

export class QywxFocus extends Service<Services> {
  private get auth() {
    return this.services.auth
  }
  private get qywxs() {
    return this.services.qywxs
  }

  /*
  - null     未确认是否要开启聚焦模式或不开启聚焦模式
  - string   要聚焦的企业微信的 wxid
  */
  protected rawFocused = new MemSubject<null | string>(null)

  /**
   * 过滤 rawFocused 的值，如果其没出现在企业微信列表里，仍视为不处于聚焦模式
   * （如果后续出现在企业微信列表里了，则自动进入聚焦模式）
   * 这样设计是因为，rawFocused 的值可能比企业微信列表更早初始化完成。
   */
  get focused() {
    return Service.cached('QywxFocus.focused', () =>
      this.rawFocused.pipe(
        mmergeMap(rawFocused =>
          this.qywxs.usables.pipe(
            mmap(usables => (rawFocused ?? '' ? usables.get(rawFocused!) ?? null : null)),
          ),
        ),
      ),
    )
  }

  registered() {
    void this.auth.accountId.then(() => {
      void this.load()
    })
  }

  protected async load() {
    const res = await API<{ SingleChatWxId: string }>('/UserConfig/GetUserConfig')
    if (res.success) this.rawFocused.next(res.data.SingleChatWxId || null)
  }

  focus(wxid: string) {
    void API('/UserConfig/SaveSingleChatWxId', { data: { SingleChatWxId: wxid } })
    this.rawFocused.next(wxid)
  }

  cancel() {
    void API('/UserConfig/SaveSingleChatWxId', { data: { SingleChatWxId: '' } })
    this.rawFocused.next(null)
  }
}
